package com.qf.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.pojo.R;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginZuulFilter extends ZuulFilter {

    //过滤器类型
    @Override
    public String filterType() {
        return "pre";
    }

    //过滤器的执行优先级,返回值越小，越优先执行
    @Override
    public int filterOrder() {
        return -5;
    }

    //是否要过滤
    @Override
    public boolean shouldFilter() {
        //判断是否是登录或者注册相关资源，如果不是，需要过滤，如果是，不用过滤
        return true;
    }

    //具体的过滤逻辑
    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();

        //获取请求对象
        HttpServletRequest request = currentContext.getRequest();

        String token = request.getParameter("token");
        if (token == null){
            //没有登录信息，非法访问 -- 阻止继续向下路由转发
            currentContext.setSendZuulResponse(false);

            //向页面返回一些友好提示
            HttpServletResponse response = currentContext.getResponse();
            response.setStatus(401);

            R r = R.error().putMsg("没有登录信息，非法访问");
            String result = JSON.toJSONString(r);

            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().write(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //这个返回值目前没有意义，主要是考虑后期框架升级扩展留的余地
        return null;
    }
}
